<template>
  <div class="common-page-content">
    <common-list style="padding: 0">
      <!--    查询区域-->
      <common-search slot="search" @search="handleQuery" @reset="resetQuery">
        <el-form
            :inline="true"
            ref="queryForm"
            :model="queryParams"
            label-width="65px"
            @submit.native.prevent
        >
          <el-form-item label="测试日志" prop="filterExample">
            <common-input
                v-model="queryParams.filterExample"
                @enter="handleQuery"
            ></common-input>
          </el-form-item>
          <el-form-item label="关键字" prop="filterKey">
            <common-input
                v-model="queryParams.filterKey"
                @enter="handleQuery"
            ></common-input>
          </el-form-item>
          <el-form-item label="表达式" prop="filterPattern">
            <common-input
                v-model="queryParams.filterPattern"
                @enter="handleQuery"
            ></common-input>
          </el-form-item>
        </el-form>
      </common-search>
      <!--      按钮-->
      <div slot="tools">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                type="primary"
                icon="el-icon-plus"
                plain
                @click="handleAdd"
                v-hasPermi="['analysiscenter:assetCategory:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="el-icon-download"
                @click="importShow"
                v-hasPermi="['analysiscenter:assetCategory:export']"
            >导入
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="el-icon-upload2"
                :loading="exportLoading"
                @click="handleExport"
                v-hasPermi="['analysiscenter:assetCategory:export']"
            >导出
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="danger"
                icon="el-icon-delete"
                plain
                :disabled="!showBatch"
                @click="handleDelete()"
                v-hasPermi="['analysiscenter:assetCategory:remove']"
            >批量删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="success"
                plain
                icon="el-icon-circle-check"
                :disabled="!showBatch"
                @click="handleChangeStatus(1)"
                v-hasPermi="['analysiscenter:assetCategory:updateStatus']"
            >启用
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="danger"
                plain
                icon="el-icon-remove-outline"
                :disabled="!showBatch"
                @click="handleChangeStatus(0)"
                v-hasPermi="['analysiscenter:assetCategory:updateStatus']"
            >停用
            </el-button>
          </el-col>
        </el-row>
      </div>
      <!--    列表-->
      <common-table
          slot="content"
          :data="List"
          @selection-change="handleSelectionChange"
          v-loading="tabLoading"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="关键字" prop="filterKey" align="left" show-overflow-tooltip/>
        <el-table-column label="可用性" prop="sort" align="left" width="100"/>
        <el-table-column label="类型" align="left" prop="isDefault" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isDefault === 1" type="success"
            >预定义
          </el-tag>
          <el-tag v-if="scope.row.isDefault === 0" type="warning">自定义</el-tag>
        </template>
      </el-table-column>
        <el-table-column label="备注" prop="remark" align="left" show-overflow-tooltip/>
        <el-table-column label="状态" align="left" prop="activeState">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.activeState===1">启用</el-tag>
            <el-tag type="danger" v-if="scope.row.activeState===0">停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column
            label="操作"
            width="160px"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="getInfo(scope.row)"
            >详情
            </el-button>
            <el-button
                type="text"
                @click="handleShake(scope.row)"
                :disabled="scope.row.isDisabledForShake"
            >
              <span v-if="scope.row.activeState===0">启用</span>
              <span v-if="scope.row.activeState===1">停用</span>
            </el-button>
            <el-button
                type="text"
                @click="edit(scope.row)"
                v-hasPermi="['analysiscenter:assetCategory:edit']"
            >编辑
            </el-button>
            <el-button
                type="text"
                @click="handleDelete(scope.row)"
                v-hasPermi="['analysiscenter:assetCategory:remove']"
                v-if="scope.row.isDefault===0"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </common-table>
      <!--  详情-->
      <common-info-dialog
        :visible="openInfo"
        :title="infoTitle"
        @cancel="cancelInfo"
        :infoLoading="infoLoading"
      >
        <common-info-table>
          <common-info-table-cell label="关键字">{{info.filterKey}}</common-info-table-cell>
          <common-info-table-cell label="表达式">{{info.filterPattern}}</common-info-table-cell>
          <common-info-table-cell label="测试日志">{{info.filterExample}}</common-info-table-cell>
          <common-info-table-cell label="可用性">{{info.sort}}</common-info-table-cell>
          <common-info-table-cell label="备注">{{info.remark}}</common-info-table-cell>
        </common-info-table>
      </common-info-dialog>
      <!--     导入-->
      <common-upload-dialog
          report-path="analysiscenter/source/downErrorReportByemplateName"
          upload-path="/analysiscenter/parserrule/importAssetCategory"
          acceptType=".txt"
          ref="uploadDialog"
          :uploadData="uploadData"
          :getList="getList"
      />
      <pagination
          slot="pagination"
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
      />
    </common-list>
    <template v-if="ishowAddConfigure">
      <add-configure
          @closeView="closeAddConfigure"
          :title="isTitle"
          :label="label"
          @submit="submitForm"
          :configureId="configureId"
          :configureData="configureFormData"
          :configAddId="configureViewId"
          :addConfigureParentId="addConfigureParentId"
      >
      </add-configure>
    </template>
  </div>
</template>

<script>
import BaseList from '@/mixins/BaseList'
import addConfigure from '@/views/analysisCenter/assetsType/components/components/addconfigure'
import
{
  configureList,
  configureDelete,
  configureEdit,
  queryDetail,
  updateStatus
} from '@/api/analysisCenter/configure'

export default {
  name: 'list',
  mixins: [BaseList],
  components: {
    addConfigure
  },
  props: {
    configureViewId: {
      type: [Number, String],
      default: null
    },
    addConfigureParentId:{
      type:String,
      default: ''
    },
    label: {
      type:String,
      default: null,
    },
  },
  watch: {
    configureViewId: {
      handler(newVal, oldVal) {
        if(newVal !== oldVal){
          this.queryParams.pageNum = 1
        }
        this.getList()
        this.uploadContent()
      },
      deep: true,
      immediate: true
    },
  },
  data() {
    return {
      exportLoading: false,
      info:{
        filterKey:'',
        remark:'',
        filterPattern:'',
        filterExample:'',
        sort:''
      },
      openInfo:false,
      infoTitle:'',
      infoLoading:false,
      uploadData: {},
      tabLoading: false,
      total: 0,
      configureId: null,
      ishowAddConfigure: false,
      isTitle: false,
      queryParams: {
        filterExample: null,
        filterKey: null,
        filterPattern: null,
        pageSize: 10,
        pageNum: 1
      },
      List: [],
      configureFormData: {},
      key: 'categoryParserruleId'
    }
  },
  methods: {
    //一键启用停用
    handleChangeStatus(type) {
      const ids = this.ids.join(',')
      const text = type === 0 ? "停用" : "启用";
      this.$confirm("是否确认" + text + "?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        updateStatus({ activeState: type, parserruleIds: ids })
            .then((res) => {
              if (res && res.code === 200) {
                this.$GlobalSuccessMessage('操作成功')
                this.getList()
              } else {
                this.$GlobalErrorConfirm('操作失败', res.msg).then()
              }
            });
      })
    },
    //
    uploadContent() {
      this.uploadData = {
        categoryId: this.configureViewId
      }
    },
    getInfo(row){
      // console.log(row)
      this.infoTitle="详情"
      this.openInfo=true
      this.getDetail(row)
    },
    getDetail(row){
      this.infoLoading=true
      queryDetail({categoryParserruleId:row.categoryParserruleId}).then((res)=>{
        if(res && res.code === 200){
          this.info.filterKey=res.data.filterKey
          this.info.filterPattern=res.data.filterPattern
          this.info.filterExample=res.data.filterExample
          this.info.remark=res.data.remark
          this.info.sort=res.data.sort
        }else{
          this.$GlobalErrorConfirm("获取信息失败", res.msg);
        }
      }).finally(()=>{
        this.infoLoading=false
      })
    },
    cancelInfo(){
      this.openInfo=false
    },
    closeAddConfigure() {
      this.ishowAddConfigure = false
    },
    getList() {
      this.tabLoading = true
      const params = {
        ...this.queryParams,
        assetCategoryId: this.configureViewId
      }
      configureList(params).then((res) => {
        if (res && res.code === 200) {
          this.List = res.rows.reduce((r, c) => {
            r.push({
              ...c,
              isDisabledForShake: false
            })
            return r
          }, [])
          this.total = res.total
        } else {
          this.List = []
          this.total = 0
          this.handleListTips(res)
        }
      }).finally(() => {
        this.tabLoading = false
      })
    },
    //查询
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    //重置
    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
    },
    //
    submitForm() {
      this.ishowAddConfigure = false
      this.getList()
    },
    //新增
    handleAdd() {
      this.ishowAddConfigure = true
      this.isTitle = false
    },
    //编辑
    edit(row) {
      // console.log(row)
      this.isTitle = true
      this.configureId = row.categoryParserruleId
      this.configureFormData = row
      if (row.activeState === 1) {
        this.$GlobalErrorConfirm('编辑失败', '启用状态下不允许编辑')
      } else {
        this.ishowAddConfigure = true
      }
    },
    //导入
    importShow() {
      this.$refs.uploadDialog.show()
    },

    //导出
    handleExport() {
      this.exportLoading = true;
      this.download(
          '/analysiscenter/parserrule/export',
          {
            ...this.queryParams,
            pageSize: 10000,
            assetCategoryId: this.configureViewId
          },
          `配置文本${new Date().getTime()}.txt`,
          20000
      ).finally(()=>{
        this.exportLoading = false;
      })
    },
    //删除按钮
    handleDelete(row) {
      // console.log(this.ids)
      if (row) {
        //单选
        if (row.activeState === 1) { //启用状态
          this.$GlobalErrorConfirm('删除失败', '状态已启用无法删除')
        } else {
          const ids = row?.categoryParserruleId
          this.$GlobalDeleteConfirm().then(() => {
            configureDelete({ ids }).then((res) => {
              if (res && res.code === 200) {
                this.$GlobalSuccessMessage('删除成功')
                if (this.queryParams.pageNum > 1 && ids.split(',').length === this.List.length) {
                  this.queryParams.pageNum -= 1
                }
                this.getList()
              } else {
                this.$GlobalErrorConfirm('删除失败', res.msg)
              }
            })

          }).catch(()=>{});
        }
      } else {
        //多选
        let status = this.List.find(
            (v) => this.ids.includes(v.categoryParserruleId) && v.activeState === 1
        )

        let includePredefined = this.List.find(
            (v) => this.ids.includes(v.categoryParserruleId) && v.isDefault === 1
        );

        if (status) {
          return this.$GlobalErrorConfirm('删除失败', '状态已启用无法删除')
        } else if (includePredefined) {
          this.$GlobalErrorConfirm("删除失败", "包含预定义数据");
          return;
        }else {
          const ids = this.ids.join(',')
          this.$GlobalDeleteConfirm().then(() => {
            configureDelete({ ids }).then((res) => {
              if (res && res.code === 200) {
                this.$GlobalSuccessMessage('删除成功')
                if (this.queryParams.pageNum > 1 && ids.split(',').length === this.List.length) {
                  this.queryParams.pageNum -= 1
                }
                this.getList()
              } else {
                this.$GlobalErrorConfirm('删除失败', res.msg)
              }
            })
          }).catch(()=>{});
        }
      }
    },
    //停用启用
    changeStatus(row) {
      return new Promise((resolve, reject) => {
        let activeState = row.activeState === 1 ? 0 : 1
        updateStatus({ activeState: activeState, parserruleIds: row.categoryParserruleId })
            .then((res) => {
              if (res && res.code === 200) {
                this.$GlobalSuccessMessage('操作成功')
                this.getList()
                resolve(res)
              } else {
                this.$GlobalErrorConfirm('操作失败', res.msg).then()
                reject()
              }
            }).catch(() => reject());
      })
    }
  },
  mounted() {
  }
}
</script>

<style scoped lang="scss">
.common-page-content {
  height: 100%;
}
</style>
